package io.renren.modules.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.sp.dao.*;
import io.renren.modules.sp.dto.SpMatchAreaLimitDTO;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.service.SpMatchAreaLimitService;
import io.renren.modules.sys.dao.SysCommDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 赛事省份人数限制
 *
 * @author whc 1@1.com
 * @since 3.0 2025-01-22
 */
@Service
public class SpMatchAreaLimitServiceImpl extends CrudServiceImpl<SpMatchAreaLimitDao, SpMatchAreaLimitEntity, SpMatchAreaLimitDTO> implements SpMatchAreaLimitService {

    @Autowired
    private SpMatchItemDao spanItemDao;
    @Autowired
    private SpMatchAreaLimitDao spMatchAreaLimitDao;
    @Autowired
    private SpBaseMatchItemDao baseMatchItemDao;
    @Autowired
    private SpMatchItemDao matchItemDao;
    @Autowired
    private SpMatchDao matchDao;
    @Autowired
    private SysCommDao sysCommDao;
    @Autowired
    private TAreaDao areaDao;

    @Override
    public QueryWrapper<SpMatchAreaLimitEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<SpMatchAreaLimitEntity> wrapper = new QueryWrapper<>();
        //matchId
        wrapper.eq(params.get("matchId") != null, "match_id", params.get("matchId"));


        return wrapper;
    }

    @Override
    public List<SpMatchAreaLimitEntity> queryWrapper(QueryWrapper wrapper) {
        return this.baseDao.selectList(wrapper);
    }

    @Override
    public void validateDate(SpMatchAreaLimitDTO dto) {
        //查询实体
        String cc = "select count(1) from sp_match t\n" +
                "left join sp_match_item ti on ti.match_id = t.id\n" +
                "left join sp_base_match_item bi on bi.id = ti.base_match_item_id\n" +
                "where ti.id =#{p.matchItemId} and t.match_level =2";
        Map<String, Object> p = new HashMap<>();
        p.put("matchItemId", dto.getMatchItemId());
        //查询已报名
        int signNum = sysCommDao.count(cc, new HashMap<String, Object>());
        if (dto.getNum() != null && signNum > dto.getNum()) {
            throw new RuntimeException("不能小于当前报名人数" + signNum);
        }
    }

    //校验赛事ID和赛项ID是否匹配
    /*@Override
    public List<SpMatchItemEntity> checkMatchItem(Integer matchId, String matchItemId) {
        List<SpMatchItemEntity> list = spanItemDao.selectList(new QueryWrapper<SpMatchItemEntity>()
                .eq("match_id", matchId)
                .eq("base_match_item_id", matchItemId)
        );
        return list;
    }*/


    /**
     * 校验赛项，超额时无法点击推荐晋级/推荐直通
     *
     * @param matchItemId
     * @return true:超额 false：未超
     */
    @Override
    public boolean checkLimitNum(Integer matchItemId) {
        //查询赛项下某个省份的报名人数
        int signNum = spMatchAreaLimitDao.queryUserNum(matchItemId);
        //查询配置的人数
        int limitNum = spMatchAreaLimitDao.selectOne(new QueryWrapper<SpMatchAreaLimitEntity>()
                .eq("match_item_id", matchItemId)
        ).getNum();
        if (signNum >= limitNum) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> queryMatchAreaLimit(Integer matchId, String matchItemId) {
        return spMatchAreaLimitDao.queryMatchAreaLimit(matchId, matchItemId);
    }

    @Override
    public List<SpMatchAreaLimitEntity> queryBy(Integer matchId, Integer matchItemId) {
        return spMatchAreaLimitDao.queryBy(matchId, matchItemId);
    }

    //根据赛项ID+赛项名称查询id
    @Override
    public Long queryMatchItemId(Integer matchId, String matchItemName) {
        SpBaseMatchItemEntity entity = baseMatchItemDao.selectOne(
                new QueryWrapper<SpBaseMatchItemEntity>()
                        .eq("item_name", matchItemName)
        );
        if (entity != null) {
            SpMatchItemEntity matchItemEntity = matchItemDao.selectOne(
                    new QueryWrapper<SpMatchItemEntity>()
                            .eq("base_match_item_id", entity.getId())
                            .eq("match_id", matchId)
            );
            return matchItemEntity.getId();
        } else {
            return null;
        }
    }

    @Override
    public List<SpMatchAreaLimitEntity> findByMatchId(Integer matchId) {
        return spMatchAreaLimitDao.findByMatchId(matchId);
    }

    @Override
    public List<Map<String, String>> querySpMatchLimit(String season) {
        String sql = "select t.match_name,r.`name`,bi.item_name,FORMAT(sl.num,0) num " +
                " ,FORMAT(t.id,0) match_id" +
                " ,FORMAT(ti.id,0) match_item_id " +
                " ,t.province " +
                " , format((SELECT count(1) from sp_match_item_team_user stm " +
                "left join sp_match_item_team mi on mi.id = stm.match_item_team_id " +
                "where stm.type=1 and mi.is_rise = 1 and mi.match_item_id = ti.id ),0) have_num " +
                " from sp_match t " +
                "left join sp_match_item ti on ti.match_id = t.id " +
                "left join sp_base_match_item bi on bi.id = ti.base_match_item_id " +
                "left join t_area r on r.code = t.province " +
                "left join sp_match_area_limit sl on sl.match_item_id = ti.id " +
                "where t.season=#{p.season} and t.match_level=2";
        Map<String, Object> p = new HashMap<>();
        p.put("season", season);
        return sysCommDao.commList(sql, p);
    }

    @Override
    public PageData<SpMatchAreaLimitDTO> matchItemPage(@RequestParam Map<String, Object> params) {
        Page pk = createPage(params);
        String sql = "select t.match_name,r.`name`,bi.item_name,FORMAT(sl.num,0) num " +
                " ,FORMAT(t.id,0) match_id" +
                " ,ti.id match_item_id " +
                " ,FORMAT(sl.id,0) id " +
                " ,FORMAT(sl.num,0) slnum " +
                " ,t.province " +
                " , format((SELECT count(1) from sp_match_item_team_user stm\n" +
                "left join sp_match_item_team mi on mi.id = stm.match_item_team_id\n" +
                "where stm.type=1 and stm.`status` not in (3,7,8) and mi.match_item_id = ti.id ),0) have_num " +
                " from sp_match t\n" +
                "left join sp_match_item ti on ti.match_id = t.id\n" +
                "left join sp_base_match_item bi on bi.id = ti.base_match_item_id\n" +
                "left join  t_area r on r.code = t.province\n" +
                "left join sp_match_area_limit sl on sl.match_item_id = ti.id\n" +
                "where t.id =#{p.matchId} and t.match_level =2";
        Map<String, Object> p = new HashMap<>();
        Long matchId = Long.valueOf(params.get("matchId").toString());

        p.put("matchId", matchId);
        cn.hutool.db.Page pk2 = new cn.hutool.db.Page();
        pk2.setPageNumber((int) pk.getCurrent());
        pk2.setPageSize((int) pk.getSize());
        List<Map<String, Object>> r = sysCommDao.page(pk2, sql, p);
        List<SpMatchAreaLimitDTO> list = new ArrayList<>();
        for (Map<String, Object> map : r) {
            SpMatchAreaLimitDTO dto = new SpMatchAreaLimitDTO();
            dto.setMatchItemName(map.get("item_name").toString());
            dto.setMatchItemId(Integer.parseInt(map.get("match_item_id").toString()));

            if (map.get("id") != null && !"".equals(map.get("id"))) {
                dto.setId(Long.valueOf(map.get("id").toString()));
                if (map.get("slnum") != null) {
                    dto.setNum(Integer.parseInt(map.get("slnum").toString()));

                }
            }
            list.add(dto);
        }
        String cc = "select count(1) from sp_match t\n" +
                "left join sp_match_item ti on ti.match_id = t.id\n" +
                "left join sp_base_match_item bi on bi.id = ti.base_match_item_id\n" +
                "left join  t_area r on r.code = t.province\n" +
                "left join sp_match_area_limit sl on sl.match_item_id = ti.id\n" +
                "where t.id =#{p.matchId} and t.match_level =2";
        PageData<SpMatchAreaLimitDTO> page = new PageData<SpMatchAreaLimitDTO>(list,
                sysCommDao.count(cc, p));
        return page;
    }


    @Override
    public List<String> headerList(Integer matchId) {
        return spMatchAreaLimitDao.headerList(matchId);
    }

    @Override
    public List<String> productList() {
        return spMatchAreaLimitDao.queryProvince();
    }

    @Override
    public String getProvinceCode(String name) {
        List<TAreaEntity> list = areaDao.getAreaByName(name);
        if (list.size() > 0) {
            return list.get(0).getCode();
        } else {
            return null;
        }
    }

    //去保存
    @Override
    public void toSave(SpMatchAreaLimitDTO dto) {
        SpMatchAreaLimitEntity entity = new SpMatchAreaLimitEntity();

        SpMatchItemEntity matchItemEntity = matchItemDao.selectById(dto.getMatchItemId());
        SpMatchEntity matchEntity = matchDao.selectById(matchItemEntity.getMatchId());
        entity.setMatchId(matchItemEntity.getMatchId().intValue());
        entity.setMatchItemId(dto.getMatchItemId());
        entity.setNum(dto.getNum());
        entity.setProvince(matchEntity.getProvince());
        baseDao.insert(entity);
    }

    @Override
    public List<Map<String, String>> querySpMatchLimit3(String season) {
        List<Map<String, String>> all = new ArrayList<>();

        Map<String, Object> p = new HashMap<>();
        p.put("season", season);

        //查询所有二级赛事
        String sql = "select t.id,t.match_name,r.name " +
                " from sp_match t " +
                " left join  t_area r on r.code = t.province " +
                " where t.season=#{p.season} and t.match_level=2 ";
        List<Map<String, String>> list = sysCommDao.commList(sql, p);

        //查询一级赛事的所有赛项
        String sql2 = "select t.id,bi.sort,bi.item_name, ti.base_match_item_id " +
                " from sp_match t  " +
                " LEFT JOIN sp_match_item ti ON ti.match_id = t.id " +
                " LEFT JOIN sp_base_match_item bi ON bi.id = ti.base_match_item_id " +
                " WHERE t.season = #{p.season} AND t.match_level = 1 and t.status = 1" +
                " order by bi.sort asc" ;

        List<Map<String, String>> itemList = sysCommDao.commList(sql2, p);

        //t2.match_name, r2.`name`, tmp.item_name, FORMAT(sl.num,0) num ,0 match_id, 0 match_item_id,tmp.province, 0 have_num
        //循环
        for(Map<String, String> matchEntity : list){
            for(Map<String, String> map : itemList){
                Map<String, String> item = new HashMap<>();
                item.put("match_name", matchEntity.get("match_name"));
                item.put("name", matchEntity.get("name"));
                item.put("item_name", map.get("item_name"));
                //查询一级赛事的赛项，在二级赛项中的配置数量
                Object matchId = (Object)matchEntity.get("id");

                String sql3 = "select lt.* from sp_match_area_limit lt " +
                        " left join sp_match_item mi on lt.match_item_id = mi.id " +
                        " where mi.base_match_item_id = #{p.base_match_item_id} " +
                        " and mi.match_id = #{p.match_id}";
                Map<String, Object> p3 = new HashMap<>();
                p3.put("base_match_item_id", map.get("base_match_item_id"));
                p3.put("match_id", matchId);
                List<Map<String, String>> list3 = sysCommDao.commList(sql3, p3);
                for(Map<String, String> map3 : list3){
                    Object num = map3.get("num");
                    item.put("num", num!=null?num.toString():"0");
                }
                all.add(item);
            }
        }


        return all;
    }


}
